﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using System.IO;
using System.Windows.Data;
using System.Globalization;
using System.Windows.Media.Imaging;
using System.Collections.ObjectModel;
using Microsoft.Phone.Tasks;
using BiHCurrencyConverter.Model;
using BiHCurrencyConverter.Resources;


namespace BiHCurrencyConverter
{

    public partial class MainPage : PhoneApplicationPage
    {
        // REF01-MVVM
        // public static ObservableCollection<Currency> Currencies = new ObservableCollection<Currency>();
        //static IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
        //IsolatedStorageFile fileStore = IsolatedStorageFile.GetUserStoreForApplication();
        string symSource = String.Empty;
        string symDest = String.Empty;

        // Constructor

        public MainPage()
        {
            InitializeComponent();
            BuildApplicationBar();
            App.ViewModel.InitializeCurrencyCollection();

            lpSource.DataContext = App.ViewModel.Currencies;
            lpResulting.DataContext = App.ViewModel.Currencies;

            // REF01-MVVM
            //InitializeCurrencyCollection();

            //lpSource.DataContext = Currencies;
            //lpResulting.DataContext = Currencies;
        }

        // Helper function to build a localized ApplicationBar
        private void BuildApplicationBar()
        {
            // Set the page's ApplicationBar to a new instance of ApplicationBar.
            ApplicationBar = new ApplicationBar();
            ApplicationBar.Opacity = 0.5;
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = true;

            // Create a buttons and set the text value to the localized string from AppResources.
            ApplicationBarIconButton appBarButtonConvert = new ApplicationBarIconButton(new Uri("/Images/appbar.check.rest.png", UriKind.Relative));
            appBarButtonConvert.Text = AppResources.txtConvert;
            ApplicationBar.Buttons.Add(appBarButtonConvert);
            appBarButtonConvert.Click += new EventHandler(ApplicationBarIconButton_Click);

            ApplicationBarIconButton appBarButtonSwap = new ApplicationBarIconButton(new Uri("/Images/appbar.swap2-1.rest.png", UriKind.Relative));
            appBarButtonSwap.Text = AppResources.txtSwap;
            ApplicationBar.Buttons.Add(appBarButtonSwap);
            appBarButtonSwap.Click += new EventHandler(ApplicationBarIconButton_Click_1);

            ApplicationBarIconButton appBarButtonMessage = new ApplicationBarIconButton(new Uri("/Images/appbar.feature.email.rest.png", UriKind.Relative));
            appBarButtonMessage.Text = AppResources.txtMessage;
            ApplicationBar.Buttons.Add(appBarButtonMessage);
            appBarButtonMessage.Click += new EventHandler(ApplicationBarIconButton_Click_2);

            // Create a new menu item with the localized string from AppResources.
            ApplicationBarMenuItem appBarMenuSettings = new ApplicationBarMenuItem(AppResources.PgSettingsTitle_Text);
            ApplicationBar.MenuItems.Add(appBarMenuSettings);
            appBarMenuSettings.Click += new EventHandler(ApplicationBarMenuItem_Click);

            ApplicationBarMenuItem appBarMenuAbout = new ApplicationBarMenuItem(AppResources.PgAboutTitle_Text);
            ApplicationBar.MenuItems.Add(appBarMenuAbout);
            appBarMenuAbout.Click += new EventHandler(ApplicationBarMenuItem_Click_1);

        }


        // REF01-MVVM
        //public static void InitializeCurrencyCollection()
        //{
        //    Currencies.Clear();
        //    foreach (var item in settings)
        //    {
        //        Currencies.Add(new Currency
        //        {
        //            Symbol = item.Key.ToString(),
        //            Rate = Convert.ToDouble(item.Value),
        //            ImageUrl = "/images/flags/" + item.Key.ToString() + ".png"
        //        });
        //    }
        //}


        private void tbSrcValue_GotFocus(object sender, RoutedEventArgs e)
        {
            tbSrcValue.Text = "";
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            try
            {
                ContentPanel.Focus();
                CalculateAmount();
            }
            catch (Exception)
            {
                NotifyError();
            }
        }

        private void CalculateAmount()
        {
            double numAmount = 0.0;
            double numResult = 0.0;
            double numSource = 1.0;
            double numDest = 1.0;

            Currency ers = lpSource.SelectedItem as Currency;
            Currency erd = lpResulting.SelectedItem as Currency;

            
            
            if (ers != null)
            {
                //numSource = SetupExchangeRateFormat(ers.Rate);
                //numSource = Convert.ToDouble(string.Format(nfi, "{0:c}", ers.Rate));
                numSource = ers.Rate;
                
                symSource = ers.Symbol;
            }

            if (erd != null)
            {
                //numDest = Convert.ToDouble(string.Format(nfi, "{0:c}", erd.Rate));
                //numDest = SetupExchangeRateFormat(erd.Rate);

                numDest = erd.Rate;
                symDest = erd.Symbol;
            }

            numAmount = Convert.ToDouble(tbSrcValue.Text.Replace(".", CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator));
            numResult = (numDest / numSource) * numAmount;
            tbResult.Text = string.Format("{0:f2}", numResult);

        }

        double SetupExchangeRateFormat(double sourceRate)
        {
            NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat;
            nfi = (NumberFormatInfo)nfi.Clone();
            //nfi.CurrencySymbol = "";
            string numSeparator = nfi.CurrencyDecimalSeparator;
            string tmpString;
            double returnValue;
            if (numSeparator != ".")
            {
                tmpString = sourceRate.ToString().Replace(".", numSeparator);
                returnValue = Convert.ToDouble(tmpString);
            }
            else
            {
                returnValue = sourceRate;
            }

            return returnValue;


        }

        PhoneApplicationService phoneAppService = PhoneApplicationService.Current;

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            phoneAppService.State["ValueToConvert"] = tbSrcValue.Text;
            phoneAppService.State["SourceCurrency"] = lpSource.SelectedIndex;
            phoneAppService.State["ResultingCurrency"] = lpResulting.SelectedIndex;
            base.OnNavigatedFrom(e);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            object valToConvert;


            if (phoneAppService.State.ContainsKey("ValueToConvert"))
            {
                if (phoneAppService.State.TryGetValue("ValueToConvert", out valToConvert))
                {
                    tbSrcValue.Text = valToConvert.ToString();
                }
            }

            object sourceCurrency;

            if (phoneAppService.State.ContainsKey("SourceCurrency"))
            {
                if (phoneAppService.State.TryGetValue("SourceCurrency", out sourceCurrency))
                {
                    // MessageBox.Show(lpSource.SelectedIndex.ToString());
                    lpSource.SelectedIndex = Convert.ToInt32(sourceCurrency);
                }
            }

            object resultingCurrency;

            if (phoneAppService.State.ContainsKey("ResultingCurrency"))
            {
                if (phoneAppService.State.TryGetValue("ResultingCurrency", out resultingCurrency))
                {
                    lpResulting.SelectedIndex = Convert.ToInt32(resultingCurrency);
                }
            }




            base.OnNavigatedTo(e);
        }

        //private void btnRefreshData_Click(object sender, RoutedEventArgs e)
        //{
        //    WebClient webClient = new WebClient();
        //    webClient.DownloadStringAsync(new Uri("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"));
        //    webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
        //}

        //void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        //{
        //    XDocument xmlResult = XDocument.Parse(e.Result);
        //    IsolatedStorageFileStream stream = new IsolatedStorageFileStream("eurofxref-daily.xml", FileMode.Truncate, FileAccess.ReadWrite, fileStore);
        //    try
        //    {
        //        StreamWriter writeFile = new StreamWriter(stream);
        //        xmlResult.Save(writeFile);
        //        writeFile.Close();
        //    }
        //    catch (Exception)
        //    {
        //        MessageBox.Show("Unable to update rates. Error 55.");
        //    }

        //    IsolatedStorageFileStream streamRead = fileStore.OpenFile("eurofxref-daily.xml", FileMode.OpenOrCreate);
        //    //StreamReader readFile = null;
        //    try
        //    {
        //        XDocument dataDoc = XDocument.Load(streamRead);
        //        XNamespace gesmes = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref";

        //        var quotes = from cube1 in dataDoc.Descendants(gesmes + "Cube")
        //                     from cube2 in cube1.Descendants(gesmes + "Cube")
        //                     from cube3 in cube2.Descendants(gesmes + "Cube")
        //                     select new ExchangeRates { Symbol = cube3.Attribute("currency").Value, Rate = double.Parse(cube3.Attribute("rate").Value) }; ;

        //        if (!settings.Contains("BAM"))
        //        {
        //            settings["BAM"] = 1.95583;
        //        }

        //        if (!settings.Contains("EUR"))
        //        {
        //            settings["EUR"] = 1.0;
        //        }

        //        foreach (var item in quotes)
        //        {                    
        //                settings[item.Symbol] = item.Rate; 
        //        }
        //    }
        //    catch (Exception)
        //    {
        //        MessageBox.Show("Unable to update rates. Error 56.");
        //    }            

        //    MessageBox.Show("Succeeded");
        //}

        private void lpSource_Loaded(object sender, RoutedEventArgs e)
        {
            //if (lpSource.SelectedIndex  null)
            //{
            //    lpSource.SelectedIndex = 0;    
            //}

            //int lpS = lpSource.SelectedIndex;

        }

        private void lpResulting_Loaded(object sender, RoutedEventArgs e)
        {

            //lpResulting.SelectedIndex = 0;
        }

        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.RelativeOrAbsolute));
        }

        private void ApplicationBarMenuItem_Click_1(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/About.xaml", UriKind.RelativeOrAbsolute));
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            try
            {
                var tempVar = lpResulting.SelectedIndex;
                lpResulting.SelectedIndex = lpSource.SelectedIndex;
                lpSource.SelectedIndex = tempVar;
            }
            catch (Exception)
            {
                NotifyError();
            }

        }





        private void CreateSMS()
        {
            if (tbSrcValue.Text == String.Empty)
            {
                NotifyUser();
                return;
            }

            if (tbResult.Text == String.Empty)
            {
                NotifyUser();
                return;

            }

            if (symSource == String.Empty)
            {
                NotifyUser();
                return;
            }

            if (symDest == String.Empty)
            {
                NotifyUser();
                return;
            }

            PhoneNumberChooserTask recipientSelect = new PhoneNumberChooserTask();
            recipientSelect.Completed += new EventHandler<PhoneNumberResult>(recipientSelect_Completed);
            recipientSelect.Show();

        }



        void recipientSelect_Completed(object sender, PhoneNumberResult e)
        {

            //only continue if the user selected a contact
            if (e.TaskResult == TaskResult.OK)
            {
                SmsComposeTask sms = new SmsComposeTask();
                sms.To = e.PhoneNumber;
                sms.Body = String.Format(AppResources.msgCurrencyConversion, tbSrcValue.Text, symSource, tbResult.Text, symDest);
                sms.Show();

            }

        }


        private static void NotifyUser()
        {
            MessageBox.Show(AppResources.msgNotifySms);
        }

        private static void NotifyError()
        {
            MessageBox.Show(AppResources.msgNotifyError);
        }

        private void ApplicationBarIconButton_Click_2(object sender, EventArgs e)
        {
            try
            {
                CreateSMS();
            }
            catch (Exception)
            {
                NotifyError();
            }
        }



        //bool navigationPerformed = true;
    }


    //public sealed class ImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { try { return new BitmapImage(new Uri((string)value)); } catch { return new BitmapImage(); } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }

}